//
//  MyCollectionViewController.m
//  HuiKaoClient
//
//  Created by 龚 杰 on 13-2-26.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "MyCollectionViewController.h"
#import "MainTabBarController.h"
#import "MyCollectionCell.h"
#import "AppDelegate.h"
#import "WebNewsViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface MyCollectionViewController ()

@end

@implementation MyCollectionViewController


- (id)init
{
    if (self = [super init]) {
        m_MyFavDataArray = [[NSMutableArray alloc] init];
        m_page = 1;
        isLook = YES;
        isRefresh = NO;

    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if([m_titleBttBarItem superview] == nil){
        [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
    }
    if ([m_BackBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_BackBttBarItem];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([m_titleBttBarItem superview]) {
        [m_titleBttBarItem removeFromSuperview];
    }
    if ([m_BackBttBarItem superview]) {
        [m_BackBttBarItem removeFromSuperview];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    m_titleBttBarItem = [[MainTabBarController setTitle:@"我的收藏"] retain];
    
    m_BackBttBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    m_BackBttBarItem.frame = CGRectMake(5, 7, 50, 30);
    [m_BackBttBarItem setBackgroundImage:[UIImage imageNamed:@"button_back.png"] forState:UIControlStateNormal];
    [m_BackBttBarItem setTitle:@"返回" forState:UIControlStateNormal];
    [m_BackBttBarItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    m_BackBttBarItem.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [m_BackBttBarItem addTarget:self action:@selector(navBackBtt) forControlEvents:UIControlEventTouchUpInside];
    [m_BackBttBarItem retain];

    
    m_COTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-49) style:UITableViewStylePlain];
//    m_COTableview.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//    m_COTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView* iview = [[UIView alloc] initWithFrame:m_COTableview.frame];
    [iview setBackgroundColor:[UIColor colorWithRed:242/250.f green:242/255.0f blue:242/255.0f alpha:1.0]];
    m_COTableview.backgroundView = iview;
    [iview release];
    [m_COTableview setDataSource:self];
    [m_COTableview setDelegate:self];
    
    
    m_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - m_COTableview.bounds.size.height, m_COTableview.bounds.size.width, m_COTableview.bounds.size.height)];
    m_refreshHeaderView.delegate = self;
    [m_COTableview addSubview:m_refreshHeaderView];
    [m_refreshHeaderView refreshLastUpdatedDate];
    [self.view addSubview:m_COTableview];
    NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
    m_Userid = [tUserDef objectForKey:USER_ID];
    [self requestPageData];
    [self addHudLoad];

}
-(void)navBackBtt
{
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)requestPageData
{
    if (isLook) {
        isLook = NO;
        HttpInterfaceManager* iHttpInterface = [HttpInterfaceManager sharedManager];
        iHttpInterface.delegate = self;
        NSString* ipage = [NSNumber numberWithInt:m_page].stringValue;
        [iHttpInterface GetMyFavListRequestGet:m_Userid target:@"new" page:ipage pageSize:@"20"];
    }
}


#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [m_MyFavDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* tCellstr = @"MyOCell";
    MyCollectionCell* tCell = [tableView dequeueReusableCellWithIdentifier:tCellstr];
    if (tCell == nil) {
        tCell = [[[MyCollectionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tCellstr] autorelease];

        tCell.accessoryType = UITableViewCellAccessoryNone;
        tCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSInteger row = indexPath.row;
    NSLog(@"row = %d",row);
    NSLog(@"count = %d",[m_MyFavDataArray count]);
    NSDictionary* dic = (NSDictionary*)[m_MyFavDataArray objectAtIndex:row];
    NSString* title  =[dic objectForKey:@"title"];
    NSString* category = [dic objectForKey:@"category"];
    NSString* created = [dic objectForKey:@"created"];
    NSString* url = [dic objectForKey:@"image"];
    [tCell setIsImageAndtext:url title:title time:[NSString stringWithFormat:@"%@  %@",category,created]];
    return tCell;
}


#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 58;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSDictionary* tDic = [m_MyFavDataArray objectAtIndex:indexPath.row];
    if (tDic!=nil) {
        NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getNewsDetail&id=%d&cur_user_id=%d",RequestCurrentURL,[[tDic objectForKey:@"id"] intValue],m_Userid.intValue];
        NSString*  tNewsID = [tDic objectForKey:@"id"];
        WebNewsViewController* tWebNewsVC = [[WebNewsViewController alloc] init];
        tWebNewsVC.m_HttpURL =tURLStr;
        tWebNewsVC.m_NewsID = tNewsID;
        tWebNewsVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tWebNewsVC animated:YES];
        [tWebNewsVC release];
    }

}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[m_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    int tShowH =0;
    if ([scrollView isEqual:m_COTableview]) {
        [m_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
        tShowH = scrollView.contentOffset.y+scrollView.frame.size.height;
        if (scrollView.contentOffset.y > 0&&tShowH > scrollView.contentSize.height+60&&isLook) {
            m_page++;
            [self requestPageData];
        }
    }
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
    m_page = 1;
    isRefresh = YES;
    [self requestPageData];

}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return m_reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	m_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	m_reloading = NO;
	[m_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:m_COTableview];
	
}
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    m_MBHUD.delegate = nil;
	[m_MBHUD removeFromSuperview];
	[m_MBHUD release];
	m_MBHUD=nil;
}

-(void) addHudLoad{
	if (m_MBHUD == nil) {
		m_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
		[tAppDel.window addSubview:m_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		m_MBHUD.delegate = self;
		m_MBHUD.labelText = @"请求数据中...";
		[m_MBHUD show:YES];
	}
}
#pragma mark HttpInterfaceManageDelegate
-(void)RequestResultsGetMyFav:(NSDictionary*)dic
{
    [self hudWasHidden:nil];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.2f];
    if (dic != nil) {
        if (isRefresh) {
            [m_MyFavDataArray removeAllObjects];
        }
        NSArray* iArray = [dic objectForKey:@"list"];
        if ([iArray count]>0) {
            
            for (NSDictionary* dic in iArray) {
                [m_MyFavDataArray addObject:dic];
            }
            [m_COTableview reloadData];
        }else{
            if (m_page>1) {
                m_page--;
            }
        }
    }
    
    isLook = YES;
    isRefresh = NO;
}
-(void)RequestResultsErrer:(NSDictionary*)dic
{
    [self hudWasHidden:nil];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"error_msg"] isCue:YES delayTime:2.0f];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.0f];
    isRefresh =NO;
    isLook = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [m_BackBttBarItem release];
    [m_titleBttBarItem release];
    [m_COTableview release];
    m_refreshHeaderView.delegate = nil;
    [m_refreshHeaderView release];
    m_MBHUD = nil;
    m_Userid = nil;
    [m_MyFavDataArray release];
    [super dealloc];
}
@end
